// Copyright (c) Lawrence Livermore National Security, LLC and other VisIt
// Project developers.  See the top-level LICENSE file for dates and other
// details.  No copyright assignment is required to contribute to VisIt.

#include <PyDeferExpressionAttributes.h>
#include <ObserverToCallback.h>
#include <stdio.h>
#include <Py2and3Support.h>

// ****************************************************************************
// Module: PyDeferExpressionAttributes
//
// Purpose:
//   Attributes for the DeferExpression operator
//
// Note:       Autogenerated by xml2python. Do not modify by hand!
//
// Programmer: xml2python
// Creation:   omitted
//
// ****************************************************************************

//
// This struct contains the Python type information and a DeferExpressionAttributes.
//
struct DeferExpressionAttributesObject
{
    PyObject_HEAD
    DeferExpressionAttributes *data;
    bool        owns;
    PyObject   *parent;
};

//
// Internal prototypes
//
static PyObject *NewDeferExpressionAttributes(int);
std::string
PyDeferExpressionAttributes_ToString(const DeferExpressionAttributes *atts, const char *prefix, const bool forLogging)
{
    std::string str;
    char tmpStr[1000];

    {   const stringVector &exprs = atts->GetExprs();
        snprintf(tmpStr, 1000, "%sexprs = (", prefix);
        str += tmpStr;
        for(size_t i = 0; i < exprs.size(); ++i)
        {
            snprintf(tmpStr, 1000, "\"%s\"", exprs[i].c_str());
            str += tmpStr;
            if(i < exprs.size() - 1)
            {
                snprintf(tmpStr, 1000, ", ");
                str += tmpStr;
            }
        }
        snprintf(tmpStr, 1000, ")\n");
        str += tmpStr;
    }
    return str;
}

static PyObject *
DeferExpressionAttributes_Notify(PyObject *self, PyObject *args)
{
    DeferExpressionAttributesObject *obj = (DeferExpressionAttributesObject *)self;
    obj->data->Notify();
    Py_INCREF(Py_None);
    return Py_None;
}

/*static*/ PyObject *
DeferExpressionAttributes_SetExprs(PyObject *self, PyObject *args)
{
    DeferExpressionAttributesObject *obj = (DeferExpressionAttributesObject *)self;

    stringVector vec;

    if (PyUnicode_Check(args))
    {
        char const *val = PyUnicode_AsUTF8(args);
        std::string cval = std::string(val);
        if (val == 0 && PyErr_Occurred())
        {
            PyErr_Clear();
            return PyErr_Format(PyExc_TypeError, "arg not interpretable as C++ string");
        }
        vec.resize(1);
        vec[0] = cval;
    }
    else if (PySequence_Check(args))
    {
        vec.resize(PySequence_Size(args));
        for (Py_ssize_t i = 0; i < PySequence_Size(args); i++)
        {
            PyObject *item = PySequence_GetItem(args, i);

            if (!PyUnicode_Check(item))
            {
                Py_DECREF(item);
                return PyErr_Format(PyExc_TypeError, "arg %d is not a unicode string", (int) i);
            }

            char const *val = PyUnicode_AsUTF8(item);
            std::string cval = std::string(val);

            if (val == 0 && PyErr_Occurred())
            {
                Py_DECREF(item);
                PyErr_Clear();
                return PyErr_Format(PyExc_TypeError, "arg %d not interpretable as C++ string", (int) i);
            }
            Py_DECREF(item);

            vec[i] = cval;
        }
    }
    else
        return PyErr_Format(PyExc_TypeError, "arg(s) must be one or more string(s)");

    obj->data->GetExprs() = vec;
    // Mark the exprs in the object as modified.
    obj->data->SelectExprs();

    Py_INCREF(Py_None);
    return Py_None;
}

/*static*/ PyObject *
DeferExpressionAttributes_GetExprs(PyObject *self, PyObject *args)
{
    DeferExpressionAttributesObject *obj = (DeferExpressionAttributesObject *)self;
    // Allocate a tuple the with enough entries to hold the exprs.
    const stringVector &exprs = obj->data->GetExprs();
    PyObject *retval = PyTuple_New(exprs.size());
    for(size_t i = 0; i < exprs.size(); ++i)
        PyTuple_SET_ITEM(retval, i, PyString_FromString(exprs[i].c_str()));
    return retval;
}



PyMethodDef PyDeferExpressionAttributes_methods[DEFEREXPRESSIONATTRIBUTES_NMETH] = {
    {"Notify", DeferExpressionAttributes_Notify, METH_VARARGS},
    {"SetExprs", DeferExpressionAttributes_SetExprs, METH_VARARGS},
    {"GetExprs", DeferExpressionAttributes_GetExprs, METH_VARARGS},
    {NULL, NULL}
};

//
// Type functions
//

static void
DeferExpressionAttributes_dealloc(PyObject *v)
{
   DeferExpressionAttributesObject *obj = (DeferExpressionAttributesObject *)v;
   if(obj->parent != 0)
       Py_DECREF(obj->parent);
   if(obj->owns)
       delete obj->data;
}

static PyObject *DeferExpressionAttributes_richcompare(PyObject *self, PyObject *other, int op);
PyObject *
PyDeferExpressionAttributes_getattr(PyObject *self, char *name)
{
    if(strcmp(name, "exprs") == 0)
        return DeferExpressionAttributes_GetExprs(self, NULL);


    // Add a __dict__ answer so that dir() works
    if (!strcmp(name, "__dict__"))
    {
        PyObject *result = PyDict_New();
        for (int i = 0; PyDeferExpressionAttributes_methods[i].ml_meth; i++)
            PyDict_SetItem(result,
                PyString_FromString(PyDeferExpressionAttributes_methods[i].ml_name),
                PyString_FromString(PyDeferExpressionAttributes_methods[i].ml_name));
        return result;
    }

    return Py_FindMethod(PyDeferExpressionAttributes_methods, self, name);
}

int
PyDeferExpressionAttributes_setattr(PyObject *self, char *name, PyObject *args)
{
    PyObject NULL_PY_OBJ;
    PyObject *obj = &NULL_PY_OBJ;

    if(strcmp(name, "exprs") == 0)
        obj = DeferExpressionAttributes_SetExprs(self, args);

    if (obj != NULL && obj != &NULL_PY_OBJ)
        Py_DECREF(obj);

    if (obj == &NULL_PY_OBJ)
    {
        obj = NULL;
        PyErr_Format(PyExc_NameError, "name '%s' is not defined", name);
    }
    else if (obj == NULL && !PyErr_Occurred())
        PyErr_Format(PyExc_RuntimeError, "unknown problem with '%s'", name);

    return (obj != NULL) ? 0 : -1;
}

static int
DeferExpressionAttributes_print(PyObject *v, FILE *fp, int flags)
{
    DeferExpressionAttributesObject *obj = (DeferExpressionAttributesObject *)v;
    fprintf(fp, "%s", PyDeferExpressionAttributes_ToString(obj->data, "",false).c_str());
    return 0;
}

PyObject *
DeferExpressionAttributes_str(PyObject *v)
{
    DeferExpressionAttributesObject *obj = (DeferExpressionAttributesObject *)v;
    return PyString_FromString(PyDeferExpressionAttributes_ToString(obj->data,"", false).c_str());
}

//
// The doc string for the class.
//
#if PY_MAJOR_VERSION > 2 || (PY_MAJOR_VERSION == 2 && PY_MINOR_VERSION >= 5)
static const char *DeferExpressionAttributes_Purpose = "Attributes for the DeferExpression operator";
#else
static char *DeferExpressionAttributes_Purpose = "Attributes for the DeferExpression operator";
#endif

//
// Python Type Struct Def Macro from Py2and3Support.h
//
//         VISIT_PY_TYPE_OBJ( VPY_TYPE,
//                            VPY_NAME,
//                            VPY_OBJECT,
//                            VPY_DEALLOC,
//                            VPY_PRINT,
//                            VPY_GETATTR,
//                            VPY_SETATTR,
//                            VPY_STR,
//                            VPY_PURPOSE,
//                            VPY_RICHCOMP,
//                            VPY_AS_NUMBER)

//
// The type description structure
//

VISIT_PY_TYPE_OBJ(DeferExpressionAttributesType,         \
                  "DeferExpressionAttributes",           \
                  DeferExpressionAttributesObject,       \
                  DeferExpressionAttributes_dealloc,     \
                  DeferExpressionAttributes_print,       \
                  PyDeferExpressionAttributes_getattr,   \
                  PyDeferExpressionAttributes_setattr,   \
                  DeferExpressionAttributes_str,         \
                  DeferExpressionAttributes_Purpose,     \
                  DeferExpressionAttributes_richcompare, \
                  0); /* as_number*/

//
// Helper function for comparing.
//
static PyObject *
DeferExpressionAttributes_richcompare(PyObject *self, PyObject *other, int op)
{
    // only compare against the same type 
    if ( Py_TYPE(self) != &DeferExpressionAttributesType
         || Py_TYPE(other) != &DeferExpressionAttributesType)
    {
        Py_INCREF(Py_NotImplemented);
        return Py_NotImplemented;
    }

    PyObject *res = NULL;
    DeferExpressionAttributes *a = ((DeferExpressionAttributesObject *)self)->data;
    DeferExpressionAttributes *b = ((DeferExpressionAttributesObject *)other)->data;

    switch (op)
    {
       case Py_EQ:
           res = (*a == *b) ? Py_True : Py_False;
           break;
       case Py_NE:
           res = (*a != *b) ? Py_True : Py_False;
           break;
       default:
           res = Py_NotImplemented;
           break;
    }

    Py_INCREF(res);
    return res;
}

//
// Helper functions for object allocation.
//

static DeferExpressionAttributes *defaultAtts = 0;
static DeferExpressionAttributes *currentAtts = 0;

static PyObject *
NewDeferExpressionAttributes(int useCurrent)
{
    DeferExpressionAttributesObject *newObject;
    newObject = PyObject_NEW(DeferExpressionAttributesObject, &DeferExpressionAttributesType);
    if(newObject == NULL)
        return NULL;
    if(useCurrent && currentAtts != 0)
        newObject->data = new DeferExpressionAttributes(*currentAtts);
    else if(defaultAtts != 0)
        newObject->data = new DeferExpressionAttributes(*defaultAtts);
    else
        newObject->data = new DeferExpressionAttributes;
    newObject->owns = true;
    newObject->parent = 0;
    return (PyObject *)newObject;
}

static PyObject *
WrapDeferExpressionAttributes(const DeferExpressionAttributes *attr)
{
    DeferExpressionAttributesObject *newObject;
    newObject = PyObject_NEW(DeferExpressionAttributesObject, &DeferExpressionAttributesType);
    if(newObject == NULL)
        return NULL;
    newObject->data = (DeferExpressionAttributes *)attr;
    newObject->owns = false;
    newObject->parent = 0;
    return (PyObject *)newObject;
}

///////////////////////////////////////////////////////////////////////////////
//
// Interface that is exposed to the VisIt module.
//
///////////////////////////////////////////////////////////////////////////////

PyObject *
DeferExpressionAttributes_new(PyObject *self, PyObject *args)
{
    int useCurrent = 0;
    if (!PyArg_ParseTuple(args, "i", &useCurrent))
    {
        if (!PyArg_ParseTuple(args, ""))
            return NULL;
        else
            PyErr_Clear();
    }

    return (PyObject *)NewDeferExpressionAttributes(useCurrent);
}

//
// Plugin method table. These methods are added to the visitmodule's methods.
//
static PyMethodDef DeferExpressionAttributesMethods[] = {
    {"DeferExpressionAttributes", DeferExpressionAttributes_new, METH_VARARGS},
    {NULL,      NULL}        /* Sentinel */
};

static Observer *DeferExpressionAttributesObserver = 0;

std::string
PyDeferExpressionAttributes_GetLogString()
{
    std::string s("DeferExpressionAtts = DeferExpressionAttributes()\n");
    if(currentAtts != 0)
        s += PyDeferExpressionAttributes_ToString(currentAtts, "DeferExpressionAtts.", true);
    return s;
}

static void
PyDeferExpressionAttributes_CallLogRoutine(Subject *subj, void *data)
{
    typedef void (*logCallback)(const std::string &);
    logCallback cb = (logCallback)data;

    if(cb != 0)
    {
        std::string s("DeferExpressionAtts = DeferExpressionAttributes()\n");
        s += PyDeferExpressionAttributes_ToString(currentAtts, "DeferExpressionAtts.", true);
        cb(s);
    }
}

void
PyDeferExpressionAttributes_StartUp(DeferExpressionAttributes *subj, void *data)
{
    if(subj == 0)
        return;

    currentAtts = subj;
    PyDeferExpressionAttributes_SetDefaults(subj);

    //
    // Create the observer that will be notified when the attributes change.
    //
    if(DeferExpressionAttributesObserver == 0)
    {
        DeferExpressionAttributesObserver = new ObserverToCallback(subj,
            PyDeferExpressionAttributes_CallLogRoutine, (void *)data);
    }

}

void
PyDeferExpressionAttributes_CloseDown()
{
    delete defaultAtts;
    defaultAtts = 0;
    delete DeferExpressionAttributesObserver;
    DeferExpressionAttributesObserver = 0;
}

PyMethodDef *
PyDeferExpressionAttributes_GetMethodTable(int *nMethods)
{
    *nMethods = 1;
    return DeferExpressionAttributesMethods;
}

bool
PyDeferExpressionAttributes_Check(PyObject *obj)
{
    return (obj->ob_type == &DeferExpressionAttributesType);
}

DeferExpressionAttributes *
PyDeferExpressionAttributes_FromPyObject(PyObject *obj)
{
    DeferExpressionAttributesObject *obj2 = (DeferExpressionAttributesObject *)obj;
    return obj2->data;
}

PyObject *
PyDeferExpressionAttributes_New()
{
    return NewDeferExpressionAttributes(0);
}

PyObject *
PyDeferExpressionAttributes_Wrap(const DeferExpressionAttributes *attr)
{
    return WrapDeferExpressionAttributes(attr);
}

void
PyDeferExpressionAttributes_SetParent(PyObject *obj, PyObject *parent)
{
    DeferExpressionAttributesObject *obj2 = (DeferExpressionAttributesObject *)obj;
    obj2->parent = parent;
}

void
PyDeferExpressionAttributes_SetDefaults(const DeferExpressionAttributes *atts)
{
    if(defaultAtts)
        delete defaultAtts;

    defaultAtts = new DeferExpressionAttributes(*atts);
}

